﻿using Cookbook.Models;
using Cookbook.Services;
using Microsoft.Practices.Prism.StoreApps;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.ObjectModel;
using Windows.Media.Capture;
using Windows.Storage;
using Windows.Foundation;
using System.Windows.Input;

namespace Cookbook.ViewModels
{
  public class RecipeDetailViewModel : ViewModel
  {
    private RecipeDetail recipe;

    public RecipeDetail Recipe
    {
      get { return recipe; }
      set { this.SetProperty(ref this.recipe, value); }
    }

    public ObservableCollection<string> Photos { get; set; }

    public ICommand TakePhotoCommand { get; set; }

    public RecipeDetailViewModel()
    {
      this.Photos = new ObservableCollection<string>();

      this.TakePhotoCommand = new DelegateCommand(TakePhoto);
    }

    public async Task LoadRecipeDetail(int id)
    {
      this.Recipe = await RecipeService.GetRecipeDetail(id);

      var folder = await GetRecipeFolder();
      
      if (folder != null)
      {
        var files = await folder.GetFilesAsync();
        foreach (var file in files)
        {
          this.Photos.Add(file.Path);
        }
      }
    }

    private async void TakePhoto()
    {
      var capture = new CameraCaptureUI();
      
      capture.PhotoSettings.AllowCropping = true;
      capture.PhotoSettings.CroppedAspectRatio = new Size(1, 1);

      var folder = await GetRecipeFolder(true);

      var file = await capture.CaptureFileAsync(CameraCaptureUIMode.Photo);
      await file.MoveAsync(folder);

      this.Photos.Add(file.Path);
    }

    private async Task<IStorageFolder> GetRecipeFolder(bool create = false)
    {
      var folder = await ApplicationData.Current.LocalFolder.TryGetItemAsync(this.Recipe.Id.ToString()) as IStorageFolder;
      
      if (folder == null && create)
      {
        var localFolder = ApplicationData.Current.LocalFolder;
        folder = await localFolder.CreateFolderAsync(this.Recipe.Id.ToString());
      }

      return folder;
    }
  }
}
